package nyist.media.handler;

import nyist.media.exception.BusinessException;
import nyist.media.page.ApiResult;
import nyist.media.utils.RenderUtil;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 全局异常处理器
 *
 * @author : dcf
 * @date : 2019/3/11
 */
public class SystemExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        ApiResult apiResult = null;
        String errorMsg = null;
        if (ex instanceof BusinessException) {
            BusinessException exception = (BusinessException) ex;
            errorMsg = exception.getErrorMsg();
            apiResult = exception.getApiResult();
            RenderUtil.readJson(response, apiResult, errorMsg);
        } else if (ex instanceof BindException) {
            BindException exception = (BindException) ex;
            List<ObjectError> errors = exception.getAllErrors();
            ObjectError error = errors.get(0);
            errorMsg = error.getDefaultMessage();
            RenderUtil.readJson(response, ApiResult.FAIL, errorMsg);
        }
        return modelAndView;
    }
}

